<template>
  <div>
    <vxe-modal ref="xModal" v-model="isShowAddOrUpdateEmployeeModal" title="编辑&保存" width="800" :zIndex="999" resize destroy-on-close>
      <vxe-form ref="xForm" :data="formData" :rules="formRules" title-align="right" title-width="100" @submit="submitEvent">
        <vxe-form-item title="产品信息" span="24" title-align="left" title-width="200px" :title-prefix="{icon: 'fa fa-address-card-o'}"></vxe-form-item>
        <vxe-form-item title="选择产品" span="24" :visible-method="isDetail">
          <vxe-button @click="selectPrduct">选择产品</vxe-button>
        </vxe-form-item>
        <vxe-form-item span="24" title="产品列表">
          <Row v-for="product in productList" :key="product.id">
            <Col span="6"><vxe-input v-model="product.name" readonly></vxe-input></Col>
            <Col span="6"><vxe-input v-model="product.specification" readonly></vxe-input></Col>
            <Col span="6"><vxe-input v-model="product.number" placeholder="产品数量"></vxe-input></Col>
            <Col span="4" offset="1" v-if="!isShowDetail"><Button type="error" icon="md-trash" @click="removeProduct(product.id)"></Button></Col>
          </Row>
        </vxe-form-item>
        <vxe-form-item title="客户" field="customerId" span="12" :item-render="{name: 'Select', attrs: {disabled: this.isShowDetail}, props: {filterable: true}, options: customerList}"></vxe-form-item>
        <vxe-form-item title="价格" field="price" span="12" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="收件人" field="consignee" span="12" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="手机号" field="mobilePhone" span="12" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="座机号" field="telephone" span="12" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="是否含税" field="taxInclude" span="12" :item-render="{name: 'iSwitch', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item title="送样日期" field="sendDate" span="12" :item-render="{name: 'DatePicker', attrs: {disabled: this.isShowDetail, type: 'date', format:'yyyy-MM-dd'}}"></vxe-form-item>
        <vxe-form-item title="备注" field="remark" span="24" :item-render="{name: 'input', attrs: inputAttrs}"></vxe-form-item>
        <vxe-form-item align="center" span="24" :visible-method="isDetail">
          <vxe-button type="submit" status="primary">保存</vxe-button>
          <vxe-button type="reset">重置</vxe-button>
          <vxe-button @click="close()">取消</vxe-button>
        </vxe-form-item>
      </vxe-form>
      <div v-if="isShowDetail">
        <Row>
          <Col span="12"><h4>追踪记录</h4></Col>
        </Row>
        <vxe-grid ref="vGrid"
          resizable
          border
          show-overflow
          highlight-hover-row
          row-id="id"
          :loading="tableLoading"
          :data="tableData"
          :columns="tableColumn"
        >
        </vxe-grid>
      </div>
    </vxe-modal>

    <ProductListDialog ref="ProductListDialog" @selectFinsh="selectFinsh"></ProductListDialog>
  </div>
</template>
<script>
import { sampleSendApi } from '@/api/sample-send';
import { customerApi } from '@/api/customer/customer';
import ProductListDialog from './product-list-dialog';
export default {
  name: 'SampleSendTableAdd',
  components: {
    ProductListDialog
  },
  props: {
  },
  data() {
    return {
      isShowAddOrUpdateEmployeeModal: false,
      isShowLoading: false,
      customerList: [],
      isShowDetail: false,
      productList:[],
      inputAttrs: {
        placeholder: '请输入', 
        disabled: false
      },
      formData: {
        id: 0,
        customerId: 0,
        price: '',
        consignee: '',
        mobilePhone: '',
        telephone: '',
        taxInclude: '',
        sendDate: '',
        remark: '',
        productList: []
      },
      formRules: {
        customerId: [
          { required: true, message: '客户不能为空', trigger: 'blur' }
        ],
        mobilePhone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^(13|14|15|16|17|18)\d{9}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          }
        ]
      },
      tableLoading: false,
      tableColumn: [
        {
          type: 'seq',
          width: '50'
        },
        {
          title: '时间',
          field: 'createTime'
        },
        {
          title: '人员',
          field: 'createUserName'
        },
        {
          title: '内容',
          field: 'content'
        }
      ],
      tableData: []
    };
  },
  computed: {},
  watch: {
  },
  filters: {},
  created() {
    this.getCustomerList();
  },
  mounted() {
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    selectFinsh(productList) {
      this.productList = productList;
    },
    selectPrduct() {
      this.$refs['ProductListDialog'].showModal();
    },
    removeProduct(productId) {
      for(let i = this.productList.length - 1; i>=0; i--){
        if(this.productList[i].id == productId){
          this.productList.splice(i, 1);
        }
      }
    },
    // 打开Modal
    showModal(row, isDetail) {
      if (isDetail !== undefined && isDetail) {
        this.isShowDetail = isDetail;
        this.inputAttrs.placeholder = '';
        this.inputAttrs.disabled = true;
      } else {
        this.isShowDetail = false;
        this.inputAttrs.placeholder = '请输入';
        this.inputAttrs.disabled = false;
      }
      if (row && Object.keys(row).length > 0) {
        this.formData = Object.assign({}, row);  
        if (isDetail) {
          this.getTrackLogList(row.id);
        }
        let productList = [];
        if (row.productList != undefined && row.productList.length) {
          row.productList.forEach(item => {
            productList.push({
              id: item.id,
              name: item.productName,
              specification: item.productSpecification,
              number: item.productNum
            });
          });
        }
        this.productList = productList;
      } else {
        this.formData = {};
        this.productList = [];
      }
      this.isShowAddOrUpdateEmployeeModal = true;
    },
    // isDetail
    isDetail({data, property}) {
      return !this.isShowDetail;
    },
    close() {
      this.$Modal.confirm({
        title: '友情提醒',
        content: '确定要关闭吗?关闭后表单会被重置!',
        onOk: () => {
          this.$refs.xModal.close();
        }
      });
    },
    // 点击提交
    submitEvent() {
      if (this.formData.id) {
        this.update(this.formData);
      } else {
        this.add(this.formData);
      }
    },
    // 修改成员
    async update(data) {
      try {
        if (this.productList.length <= 0) {
          this.$Message.error('请选择产品');
          return false;
        }
        let reqData = Object.assign({}, data);
        if (data.tags !== undefined) {
          reqData.tags = data.tags.join(',');
        }
        if (data.category !== undefined) {
          reqData.category = data.category[(data.category.length - 1)];
        }
        reqData.taxInclude = data.taxInclude ? 1 : 0;
        this.isShowLoading = true;
        let result = await sampleSendApi.update(reqData);
        this.isShowAddOrUpdateEmployeeModal = false;
        this.$Message.success('修改成功');
        this.$emit('addSuccess');
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowLoading = false;
      }
    },
    // 添加新用户接口
    async add(data) {
      try {
        if (this.productList.length <= 0) {
          this.$Message.error('请选择产品');
          return false;
        }
        let reqData = Object.assign({}, data);
        if (data.tags !== undefined) {
          reqData.tags = data.tags.join(',');
        }
        if (data.category !== undefined) {
          reqData.category = data.category[(data.category.length - 1)];
        }
        reqData.taxInclude = data.taxInclude ? 1 : 0;
        reqData.productList = [];
        this.productList.forEach(item => {
          reqData.productList.push({
            productId: item.id,
            productNum: parseInt(item.number)
          });
        });
        this.isShowLoading = true;
        let result = await sampleSendApi.add(reqData);
        this.isShowAddOrUpdateEmployeeModal = false;
        this.$Message.success('添加成功');
        this.$emit('addSuccess');
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowLoading = false;
      }
    },
    getCustomerList() {
      customerApi.getAll().then((response) => {
        let customerList = [];
        response.data.forEach(item => {
          customerList.push({
            value: item.id,
            label: item.name 
          });
        });
        this.customerList = customerList;
      }).catch(error => {

      });
    },
    getTrackLogList(sendId) {
      this.tableLoading = true;
      sampleSendApi.getTrackList(sendId).then(response => {
        this.tableData = response.data;
        this.tableLoading = false;
        this.inputAttrs.placeholder = '';
        this.inputAttrs.disabled = true;
      }).catch(error => {
        this.tableLoading = false;
        this.inputAttrs.placeholder = '';
        this.inputAttrs.disabled = true;
      });
    }
  }
};
</script>
